package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.Dish;
import com.itheima.dto.DishDto;
import com.itheima.domain.DishFlavor;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishService;
import com.itheima.service.FlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
implements DishService {

    @Autowired
    FlavorService flavorService;


    @Override
    public void saveWithFavlor(DishDto dto) {
        List<DishFlavor> flavors = dto.getFlavors();
        save(dto);
        Long id = dto.getId();
        List<DishFlavor> collect = flavors.stream().map((item) -> {
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        flavorService.saveBatch(collect);
    }

    @Override
    public DishDto checkById(Long id) {
        Dish DishById = getById(id);
        DishDto dishDto = new DishDto();

        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = flavorService.list(lqw);

        dishDto.setFlavors(list);

        BeanUtils.copyProperties(DishById,dishDto);

        return dishDto;
    }

    @Override
    public void updateId(DishDto dto){
        updateById(dto);
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dto.getId());

        flavorService.remove(lqw);

        List<DishFlavor> flavors = dto.getFlavors();
        flavors.stream().map((item)->{
            item.setDishId(dto.getId());
            return item;
        });
        flavorService.saveBatch(flavors);
    }

}
